package com.distributor;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ManageAgentActivity extends Activity
{
	Button btnSearch;
	EditText etSearchAgent;
	HttpConn httpConn=new HttpConn();
	private ProgressDialog pd=null;
	private Handler handler=new Handler();
	UserInfo userInfo;
	MD5Generator md5Generator=new MD5Generator();
	String SCREEN;
	Button btnBack,btnLogOut;
//	short RESELLER_LEVEL;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manage_agent); 
		
		Bundle extras = getIntent().getExtras();
		if(extras.containsKey("nextscreen"))
		{
			SCREEN=extras.getString("nextscreen");
			System.out.println("Screen:"+SCREEN);
		}			
 
		btnSearch=(Button)findViewById(R.id.btnSearchAgent);
		etSearchAgent=(EditText)findViewById(R.id.etSearchAgent);
		
		btnLogOut=(Button)findViewById(R.id.btnLogout); 
	    btnBack=(Button)findViewById(R.id.btnPrevious);
	    
	    btnLogOut.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				  new AlertDialog.Builder(ManageAgentActivity.this)
				  .setTitle( "Exit Application" )
			      .setMessage( "Are you sure you want to Logout?" )
			      .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
			       {
			           public void onClick(DialogInterface arg0, int arg1) 
			           {
			        	   setResult(2);
			               finish();
			           }

					   public void onClick(View v) 
					   {
						 // TODO Auto-generated method stub
					   }
					   
			        })
			        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
			        {
			            public void onClick(DialogInterface arg0, int arg1)
			            {
			                //do stuff onclick of CANCEL
			            	arg0.dismiss();
			            }

						public void onClick(View v) 
						{
							// TODO Auto-generated method stub
						}
			        }).show();
		  	}
			
		 });
	    
	    btnBack.setOnClickListener(new OnClickListener() 
	    {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			finish();	
			}
		});
		btnSearch.setOnClickListener(new OnClickListener() 
		{
			
			public void onClick(View arg0) 
			{
				if(etSearchAgent.getText().toString().trim().length()>0)
				{
					
					if(!SCREEN.equalsIgnoreCase("Sales Agent"))
					{
						new Thread(searchAgent,"Search Agent").start();
						pd =ProgressDialog.show(ManageAgentActivity.this,null, "Please Wait..", true);
						pd.setContentView(R.layout.progress);
					}
					else
					{
						new Thread(searchAgent,"Sales Agent").start();
						pd =ProgressDialog.show(ManageAgentActivity.this,null, "Please Wait..", true);
						pd.setContentView(R.layout.progress);
					}  
				}
				else
				{
					Toast.makeText(ManageAgentActivity.this,"Please Enter Phone Number",Toast.LENGTH_SHORT).show();
				}
			 
			}
		});
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
	    if(resultCode==1 && requestCode==22)
	    {
	    	setResult(2);
	        finish();
	    }
	}
	 
	Runnable searchAgent=new Runnable() 
	{
		
		public void run() 
		{
			try
			{
				 String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+
						  		  etSearchAgent.getText().toString()+"|"+
						  		  	AppData.getUserInfo().getpublickey() ));
				 String URL;
				  if(SCREEN.equalsIgnoreCase("Sales Agent"))
				  {
					   URL=AppData.hostURL+"/WebService/iTopUp/distributorapp.php/GetAccountInfo/LoginId/"+AppData.getUserInfo().getLoginID()
						  	  	+"/Phone1/"+etSearchAgent.getText().toString()+"/Checksum/"+checksum+"/format/json";
				  }
				  else
				  {
					   URL=AppData.hostURL+"/WebService/iTopUp/distributorapp.php/GetResellerInfo/LoginId/"+AppData.getUserInfo().getLoginID()
						  	  	+"/Phone1/"+etSearchAgent.getText().toString()+"/Checksum/"+checksum+"/format/json";  
				  }
				  
				  System.out.println("URL===>\n"+URL);
				  String response=httpConn.createHttpConn(URL);
				  System.out.println("Response:"+response);
				  final JSONObject jsonObject=new JSONObject(response);
				  
				  if(jsonObject.getString("ResponseCode").equals("000"))
	              {
					  ResellerInfo agentInfo=new ResellerInfo();
					  
					  if(jsonObject.has("AccountName"))
						  agentInfo.setAccountName(jsonObject.getString("AccountName"));
					  if(jsonObject.has("Balance"))
						  agentInfo.setBalance(""+Double.parseDouble(jsonObject.getString("Balance"))/100);
					  if(jsonObject.has("ResellerLevel"))
						  agentInfo.setResellerLevel(jsonObject.getString("ResellerLevel"));
					  if(jsonObject.has("IDProofType"))
						  agentInfo.setIDProofType(jsonObject.getString("IDProofType"));
					  if(jsonObject.has("IDNumber"))
						  agentInfo.setIDNumber(jsonObject.getString("IDNumber"));
					  if(jsonObject.has("ResellerCategory"))
						  agentInfo.setResellerCategory(jsonObject.getString("ResellerCategory"));
					  if(jsonObject.has("BillingTemplate"))
						  agentInfo.setBillingTemplate(jsonObject.getString("BillingTemplate"));
					  if(jsonObject.has("SaleExecutive"))
						  agentInfo.setSaleExecutive(jsonObject.getString("SaleExecutive"));
					  if(jsonObject.has("DiscountMatrix"))
						  agentInfo.setDiscountMatrix(jsonObject.getString("DiscountMatrix"));
					  if(jsonObject.has("Name"))
						  agentInfo.setName(jsonObject.getString("Name"));
					  if(jsonObject.has("Phone1"))
						  agentInfo.setPhone1(jsonObject.getString("Phone1"));
					  if(jsonObject.has("Phone2"))
						  agentInfo.setPhone2(jsonObject.getString("Phone2"));
					  if(jsonObject.has("IMEI"))
						  agentInfo.setIMEI(jsonObject.getString("IMEI"));
					  if(jsonObject.has("AltPhone"))
						  agentInfo.setAltPhone(jsonObject.getString("AltPhone"));
					  if(jsonObject.has("Email"))
						  agentInfo.setEmail(jsonObject.getString("Email"));
					  if(jsonObject.has("Address1"))
						  agentInfo.setAddress1(jsonObject.getString("Address1"));
					  if(jsonObject.has("Address2"))
						  agentInfo.setAddress2(jsonObject.getString("Address2"));
					  if(jsonObject.has("AreaName"))
						  agentInfo.setAreaName(jsonObject.getString("AreaName"));
					  if(jsonObject.has("AreaZipCode"))
						  agentInfo.setAreaZipCode(jsonObject.getString("AreaZipCode"));
					  if(jsonObject.has("State"))
						  agentInfo.setState(jsonObject.getString("State"));
					  if(jsonObject.has("StateName"))
						  agentInfo.setStateName(jsonObject.getString("StateName"));
					  if(jsonObject.has("MaxLevel"))
						  agentInfo.setMaxlevel(jsonObject.getString("MaxLevel"));
					 AppData.agentInfo=agentInfo;
					 
					 
					 if(SCREEN.equalsIgnoreCase("Sales Agent"))
					 {
						 pd.dismiss();
						 startActivityForResult(new Intent(ManageAgentActivity.this,ResellerInfoActivity.class),22);
					 }
					 else
					 {
						 pd.dismiss();
						 startActivityForResult(new Intent(ManageAgentActivity.this,Tab_Reseller.class).putExtra("calleractivity", 11),22);	 
					 }
		 
	              }
				  else
				  {
					  handler.post(new Runnable()
	            	  {
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							try 
							{
								Toast.makeText(ManageAgentActivity.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
	            	  });
				  }
			}
			catch(final Exception e)
			{
				handler.post(new Runnable()
          	    { 
					public void run() 
					{
						pd.dismiss();
						Toast.makeText(ManageAgentActivity.this,"",Toast.LENGTH_SHORT).show();
					}
          	    });
				e.printStackTrace();
			}
		}
	};
}
